from sqlalchemy import and_

from WebServer.blog.DB.DBValueConstants import DISABLE
from WebServer.blog.NewInterface.NOT_INIT import TagRenameMapper
from WebServer.blog.models import TagRename, DBSession_mysql, TagStatus, ENABLE

def reduce_quote(st : str):
    return st[1:-1]
def main():
    lines = []
    with open("C:/Users/hf/Desktop/服务器端备份的（包含以前的复盘数据和tag_rename/tag_rename (1).txt",mode='r',encoding='utf8') as f:
        lines = f.readlines()
    session = DBSession_mysql()
    enable_tags = set()
    for lin_ in lines:
        cells = lin_.split("\t")
        origin_ = reduce_quote(cells[0])
        to_ = reduce_quote(cells[1])
        dispose_ = reduce_quote(cells[3])
        enable_ = ENABLE if dispose_ == "-1" else DISABLE
        if to_ and enable_ == ENABLE:
            enable_tags.add(to_)
        print("o : {}  t : {} e : {} ".format(origin_, to_ , enable_))
        source_ = "人工合并"
        # 插入tag_status
        TagStatus()
        tr = TagRename(origin = origin_, to = to_, enable = enable_, source = source_)
        TagRenameMapper.insert_or_update_tag_rename(tr,session,tag_enable=DISABLE,rename_enable=enable_)
        db_obj = session.query(TagRename).filter(and_(TagRename.origin == origin_, TagRename.to == to_)).first()
        if db_obj:
            db_obj.enable = enable_
        else:
            session.add(tr)

    print("len : {} , {} ".format(len(enable_tags), enable_tags))
    for ts_obj in session.query(TagStatus).all():
        if ts_obj.tag in enable_tags:
            ts_obj.enable = ENABLE
        else:
            ts_obj.enable = DISABLE
    session.commit()
    session.close()
    pass


if __name__ == '__main__':
    main()